package com.rd.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rd.util.ResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
当没有登录或者Token失效时访问接口时,返回json数据
 AuthenticationEntryPoint
 用于处理认证失败或者未认证的请求
 当用户尝试访问受保护的资源而未经过身份验证，
 或者身份验证失败时，
 调用FilterSecurityInterceptor，
 对受保护资源的控制访问和权限验证作用，
 访问控制决策、权限验证、异常处理、
 前置处理和
 后置处理ExceptionTranslateFilter，处理身份验证和访问控制过程中的异常，
 主要捕获Spring Security中抛出的异常，并根据异常的类型来处理作用，异常处理、认证失败处理、访问拒绝处理、异常转换
 */
@Component
@Slf4j
public class RestAuthorizationEntryPoint
     implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        log.info("未登录或者Token失效时,AuthenticationEntryPoint处理器处理,返回401,尚未登录，请登录！");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ResultModel resultModel = ResultModel.createByErrorCodeMessage(401,"尚未登录，请登录！");
        out.write(new ObjectMapper().writeValueAsString(resultModel));
        out.flush();
        out.close();
    }
}
